package ChooseMethodAction;

use strict;

use Athena::WebAPI::Response;
use Athena::ChooseMethodView;
use Athena::ErrorView;

sub execute {
  my $stInvocant = shift(@_);
  my $rRequest = shift(@_);
  my $cConn = shift(@_);
  my %hParams = ( @_ );
  my $stParams = \%hParams;
  my $rResponse = undef;
  my $stErrMsg = "";
  my $stActionName = 'ChooseMethodAction';
  $rRequest->action($stActionName);
  my $stAction = $rRequest->param($stActionName);
  my $rView;
  my $stLb = $rRequest->cookie('AthenaEngineUrl') 
    || $rRequest->cookie('AthenaEngineHost') 
      . ":" . $rRequest->cookie('AthenaEnginePort');

  my $rHiddenFields = {
		       $rRequest->getActionParam() => $rRequest->action(),
		       $stActionName => '',
		      };

  # handle state change in cookies
  if ($rRequest->param('engine_method')) {
    $rRequest->cookie(-name=>'AthenaEngineMethod', '-expires'=>'+1y',
		      -value=>$rRequest->param('engine_method'));
  }
  if ($rRequest->param('engine_url')) {
    $rRequest->cookie(-name=>'AthenaEngineUrl', '-expires'=>'+1y',
		      -value=>$rRequest->param('engine_url'));
  }
  my $stUrlHistory = $rRequest->cookie('AthenaEngineUrlHistory');
  my @arUrlHistory;
  if ($stUrlHistory) {
    @arUrlHistory = split(/::/, $stUrlHistory);
    if ($rRequest->param('engine_url')) {
      my $stUrl;
      my $iAddMe = 1;
      foreach $stUrl (@arUrlHistory) {
	if ($stUrl eq $rRequest->param('engine_url')) {
	  $iAddMe = 0;
	}
      }
      if ($iAddMe) {
	if (scalar(@arUrlHistory) > 4) {
	  pop(@arUrlHistory);
	}
	unshift(@arUrlHistory, $rRequest->param('engine_url'));
      }
    }
  }
  elsif ($rRequest->param('engine_url')) {
    push(@arUrlHistory, $rRequest->param('engine_url'));
  }
  if (scalar(@arUrlHistory)) {
    $rRequest->cookie(-name=>'AthenaEngineUrlHistory', '-expires'=>'+1y',
		      -value=>join("::", @arUrlHistory));
  }
  
  if ($rRequest->param('engine_host')) {
    $rRequest->cookie(-name=>'AthenaEngineHost', '-expires'=>'+1y',
		      -value=>$rRequest->param('engine_host'));
  }
  if ($rRequest->param('engine_port')) {
    $rRequest->cookie(-name=>'AthenaEnginePort', '-expires'=>'+1y',
		      -value=>$rRequest->param('engine_port'));
  }
  

  $rView = ChooseMethodView->new('err_msg' => $stErrMsg,
				 'hidden_fields' => $rHiddenFields,
				 'action_name' => $stActionName,
				 'body_style' => $stParams->{body_style},
				 'table_style' => $stParams->{table_style},
				 'ck_engine_method' => $cConn ? $cConn->getMethod() : "not set",
				 'ck_engine_url' => $cConn ? $cConn->getUrl() : "not set",
				 'ck_engine_host' => $cConn ? $cConn->getHost() : "not set",
				 'ck_engine_port' => $cConn ? $cConn->getPort() : "not set",
				 'url_history' => \@arUrlHistory || "0"
				);
  $rResponse = Response->new($rView);
  
  return $rResponse;
}

1;
